package niu.toy.spring.mvc.impl.returnValue;


import niu.toy.spring.ioc.annotation.Nullable;
import niu.toy.spring.mvc.HandlerMethodParameter;
import niu.toy.spring.mvc.HandlerReturnValue;
import niu.toy.spring.mvc.ModelAndViewContainer;
import niu.toy.spring.mvc.NativeWebRequest;


public class ViewNameReturnValueHandler implements HandlerReturnValue {



    @Override
    public boolean supportsReturnType(HandlerMethodParameter returnType) {
        Class<?> paramType = returnType.getParameterType();
        return (void.class == paramType || CharSequence.class.isAssignableFrom(paramType));
    }

    @Override
    public void handleReturnValue(@Nullable Object returnValue, HandlerMethodParameter returnType,
                                  ModelAndViewContainer mavContainer, NativeWebRequest webRequest) throws Exception {

        if (returnValue instanceof CharSequence) {
            String viewName = returnValue.toString();
            mavContainer.setViewName(viewName);
        }
        else if (returnValue != null){
            // should not happen
            throw new UnsupportedOperationException("Unexpected return type: " +
                    returnType.getParameterType().getName() + " in method: " + returnType.getMethod());
        }
    }

}
